package com.droid.network.interceptor;

import android.content.Context;

import com.droid.base.log.Logger;
import com.droid.base.utils.NetworkUtils;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 缓存拦截器
 *
 * @author zyc0617
 * @since  2019/7/3 14:22
 */
public class CacheInterceptor implements Interceptor {

    private final static String TAG = "CacheInterceptor";
    private Context context;
    private long time = 0l;


    public CacheInterceptor(Context context){
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();//获取请求
        if (!NetworkUtils.isNetWorkConnected(context)) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
            Logger.d(TAG, "no network");
        }
        Response originalResponse = chain.proceed(request);
        if (NetworkUtils.isNetWorkConnected(context)) {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, max-age=" + 0)
                    .removeHeader("Pragma")
                    .build();
        } else {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + time)
                    .removeHeader("Pragma")
                    .build();
        }
    }

    public void setExpireTime(long time) {
        this.time = time;
    }

}
